// 显示当前标的列表状态
$(".loan_list_" + status.toLowerCase()).addClass("active");
// 初始化所有状态标的数量
var loanAmountMap = {
    PROPOSED: 0,
    REJECTED: 0,
    APPROVED: 0,
    SCHEDULED: 0,
    OPEN: 0,
    FAILED: 0,
    FINISHED: 0,
    CANCELED: 0,
    LOANED: 0,
    CLEARED: 0,
    OVERDUE: 0,
    ARCHIVED: 0
};
// 获取所有状态标的数量
function initAmountMap() {
    $.get("loan/sumByLoanStatus", function (loanStatusMap) {
        if (loanStatusMap) {
            for (var key in sysLoanStatus) {
                loanAmountMap[key] = loanStatusMap[key];
                if (loanAmountMap[key] !== 0) {
                    // 显示该状态下的标的数量
                    $(".popo-" + key.toLowerCase()).text("(" + loanAmountMap[key] + ")");
                }
            }
        } else {
            console.log(loanAmountMap);
        }
    }).fail(function (res) {
        console.log(res);
    });
}
initAmountMap();
/**
 * 不同状态排序
 * @type type
 */
var sorting = {
    PROPOSED: [[16, "desc"]], //("未处理"),
    REJECTED: [[16, "desc"]], //("未处理"),
    APPROVED: [[0, "asc"]], //("已批准"),
    SCHEDULED: [[7, "asc"]], //("已安排"),
    OPEN: [[7, "desc"]], //("开放投标"),
    FAILED: [[10, "desc"]], //("流标"),
    FINISHED: [[10, "desc"]], //("已满标"),
    CANCELED: [[0, "asc"]], //("已取消"),
    LOANED: [[11, "desc"]], //("已放款"),
    CLEARED: [[12, "desc"]], //("已还清"),
    OVERDUE: [[11, "desc"]], //("逾期");
    ARCHIVED: [[0, "asc"]]
};

// 初始化列表
var table = $('#loanList').DataTable({
//    "processing": true,
//    "serverSide": true,
    "ajax": "loan/getData/" + status,
    "columns": [
        {"data": "loan"},
        {"data": "userLoginName"},
        {"data": "loan"},
        {"data": "loan"},
        {"data": "loan"},
        {"data": "loan"},
        {"data": "loan"},
        {"data": "loan"},
        {"data": "loan"},
        {"data": "loan"},
        {"data": "loan"},
        {"data": "loan"},
        {"data": "loan"},
        {"data": "loan"},
        {"data": "loan"},
        {"data": "loan"},
        {"data": "loan"},
        {"data": "loan"}
    ],
    "aoColumnDefs": [{
            "targets": 0, //标题
            "mRender": function (loan, type, row) {
                if(loan.loanProduct==='BANK' || loan.loanProduct === 'BUSINESS' ){
                    return '<a href="bill/detail/' + loan.id + '">【票据】' + loan.title + '</a>';
                }else{
                    return '<a href="loan/detail/' + loan.id + '">【标的】' + loan.title + '</a>';
                }
            }
        }, {
            "targets": 1, //借款人
            "mRender": function (userLoginName, type, row) {
                return userLoginName === ''
                    ? '未填写'
                    : '<a href="user/index/' + row.loan.userId + '" target="_blank">' + userLoginName + '</a>';
            }
        }, {
            "targets": 2, //金额
            "mRender": function (loan, type, row) {
                return $.number(loan.amount);
            }
        }, {
            "targets": 3, //年利率
            "mRender": function (loan, type, row) {
                return $.number(parseFloat(loan.rate / 100), 1) + '%';
            }
        }, {
            "targets": 4, //借款周期
            "mRender": function (loan, type, row) {
                return sys.printDuration(loan.duration);
            }
        }, {
            "targets": 5, //还款方式
            "visible": false,
            "mRender": function (loan, type, row) {
                return sys.getRepayMethod(loan.repayMethod);
            }
        }, {
            "targets": 6, //状态
            "searchable": false,
            "mRender": function (loan, type, row) {
                return sys.getLoanStatus(loan.status);
            }
        }, {
            "targets": 7, //开标时间
            "searchable": false,
            "visible": false,
            "mRender": function (loan, type, row) {
                return '<code>' + $.format.date(new Date(loan.openTime), "yyyy/MM/dd HH:mm") + '</code>';
            }
        }, {
            "targets": 8, //筹款周期
            "searchable": false,
            "visible": false,
            "mRender": function (loan, type, row) {
                return loan.timeOut + '小时';
            }
        }, {
            "targets": 9, //投标进度
            "searchable": false,
            "visible": false,
            "mRender": function (loan, type, row) {
                var progress = (parseFloat(loan.investAmount / loan.amount) * 100).toFixed(0);
                return '<span class="badge bg-success">' + progress + ' %</span>';
            }
        }, {
            "targets": 10, //满标时间
            "searchable": false,
            "visible": false,
            "mRender": function (loan, type, row) {
                return $.format.date(new Date(loan.finishTime), "yyyy/MM/dd HH:mm");
            }
        }, {
            "targets": 11, //结标时间
            "searchable": false,
            "visible": false,
            "mRender": function (loan, type, row) {
                return $.format.date(new Date(loan.loanTime), "yyyy/MM/dd HH:mm");
            }
        }, {
            "targets": 12, //还清时间
            "searchable": false,
            "visible": false,
            "mRender": function (loan, type, row) {
                return $.format.date(new Date(loan.clearTime), "yyyy/MM/dd HH:mm");
            }
        }, {
            "targets": 13, //起息日
            "searchable": false,
            "visible": false,
            "mRender": function (loan, type, row) {
                return loan.valueDate;
            }
        }, {
            "targets": 14, //投标人数
            "searchable": false,
            "visible": false,
            "mRender": function (loan, type, row) {
                return loan.investCount;
            }
        }, {
            "targets": 15, //募集金额
            "searchable": false,
            "visible": false,
            "mRender": function (loan, type, row) {
                return $.number(loan.investAmount);
            }
        }, {
            "targets": 16, //申请时间
            "searchable": false,
            "visible": false,
            "mRender": function (loan, type, row) {
                return loan.submitTime !== null
                    ? $.format.date(new Date(loan.submitTime), "yyyy/MM/dd HH:mm")
                    : '';
            }
        }, {
            "targets": -1, //操作
            "bSortable": false,
            "searchable": false,
            "mRender": function (loan, type, row) {
                var operations = $("#operationHTML").html().replace(/#id/g, loan.id);
                if (loan.investAmount === 0) {
                    operations = operations.replace('loanLink', 'loanLink hidden');
                }
                if(loan.loanProduct==='BANK' || loan.loanProduct === 'BUSINESS' ){
                    loanProduct = loan.loanProduct;
                    operations = operations.replace('loan/detail/', 'bill/detail/');
                    operations = operations.replace('loan/edit/', 'bill/edit/');
                    operations = operations.replace('标的编辑', '票据编辑');
                    operations = operations.replace('标的放款', '票据放款');
                    operations = operations.replace('取消标的', '取消票据');
                }
                
                return operations;
            }
        }],
    "order": sorting[status],
    "oLanguage": chinese,
    "language": {
        "decimal": ",",
        "thousands": ","
    },
    "iDisplayLength": 10,
    "aLengthMenu": [
        [5, 10, 25, 50, -1],
        [5, 10, 25, 50, "全部"]
    ],
    "sDom": '<"dt-panelmenu clearfix"l<"pull-right"Tf>r>t<"dt-panelfooter clearfix"ip>',
    "oTableTools": {
        "aButtons": [{
                "sExtends": "copy",
                "sButtonText": "复制",
                "fnComplete": function (nButton, oConfig, oFlash, sFlash) {
                    alert('列表内容已复制到剪贴板');
                }
            }, {
                "sExtends": "xls",
                "sButtonText": "导出为Excel"
            }
        ],
        "sSwfPath": root_path + "/js/plugins/datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"
    },
    "initComplete": function (settings, json) {
        // 根据状态调整页面显示
        updatePage(status);
    },
    "drawCallback": function (settings) {
        makeOperations();
    }
});

function initEvents() {
    // 标的放款按钮响应事件
    $("#loanList").on("click", ".loanLink", function () {
        if (confirm("确定放款？")) {

            $.magnificPopup.open({
                removalDelay: 500, //delay removal by X to allow out-animation,
                alignTop: true,
                closeOnBgClick: false,
                items: {
                    src: "#modal"
                },
                // overflowY: 'hidden', // 
                callbacks: {
                    beforeOpen: function (e) {
                        this.st.mainClass = 'mfp-slideDown';
                    }
                },
                midClick: true // allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.
            });

            var id = $(this).data("id");
            $.post("loan/loan", {
                id: id
            }, function (res) {
                alert(res.message);
                if (res.success) {
                    location.reload();
                }
                $.magnificPopup.close();
            }).fail(function () {
                alert("服务器错误");
                $.magnificPopup.close();
            });
        }
    });
}
initEvents();
/**
 * 根据状态调整页面显示
 * @param {type} status
 * @returns {undefined}
 */
function updatePage(status) {
    // 显示所需数据列
    var columns = columnsMap[status];
    for (var i = 0; i < columns.length; i++) {
        var column = table.column(columns[i]);
        column.visible(true);
    }
    // 修复空列表显示颜色问题
    var emptyTd = $(".dataTables_empty");
    var colSpan = parseInt(emptyTd.attr('colspan')) + columns.length;
    emptyTd.attr('colspan', colSpan);
}
/**
 * 不同状态所需显示的数据列
 * @type type
 */
var columnsMap = {
    PROPOSED: [5, 16], //("未处理"),
    REJECTED: [5, 16], //("未通过"),
    APPROVED: [5, 8], //("已批准"),
    SCHEDULED: [5, 7, 8], //("已安排"),
    OPEN: [7, 8, 9, 14, 15], //("开放投标"),
    FAILED: [10, 14, 15], //("流标"),
    FINISHED: [7, 8, 9, 10, 14, 15], //("已满标"),
    CANCELED: [], //("已取消"),
    LOANED: [5, 11, 13], //("已放款"),
    CLEARED: [5, 12], //("已还清"),
    OVERDUE: [5, 11, 13], //("逾期");
    ARCHIVED: []
};
/**
 * 根据不同状态显示不同操作
 */
function makeOperations() {
    var as = $(".detailLink a");
    if (status === 'PROPOSED' || status === 'REJECTED') {
        for(var i=0;i<as.length;i++){
            var content;
            if($(as[i]).attr("href").indexOf("loan")===-1){
                content = "票据";
            }else{
                content = "标的";
            }
            $(as[i]).html('<i class="fa fa-legal mr5"></i>'+content+'审核');
        }
        $(".divider").removeClass("extra hidden");
    } else if (status === 'APPROVED') {
        for(var i=0;i<as.length;i++){
            var content;
            if($(as[i]).attr("href").indexOf("loan")===-1){
                content = "票据";
            }else{
                content = "标的";
            }
            $(as[i]).html('<i class="fa fa-clock-o mr5"></i>'+content+'排期');
        }
        $(".divider").removeClass("extra hidden");
    } else if (status === 'SCHEDULED') {
        $(".detailLink a").html('<i class="glyphicons glyphicons-restart mr5"></i>重新排期');
        $(".editLink a").html('<i class="glyphicons glyphicons-edit mr5"></i>部分编辑');
        $(".divider").removeClass("extra hidden");
        $(".cancelScheduleLink").removeClass("extra hidden");
    } else if (status === 'OPEN') {
        $(".editLink a").html('<i class="glyphicons glyphicons-edit mr5"></i>部分编辑');
        $(".divider").removeClass("extra hidden");
    } else if (status === 'FINISHED') {
        $(".settleLink").removeClass("extra hidden");
        $(".divider").removeClass("extra hidden");
        $(".cancelLink").addClass("hidden");
    } else if (status === 'FAILED') {
        $(".settleLink").removeClass("extra hidden");
        $(".divider").removeClass("extra hidden");
    } else if (status === 'LOANED') {
        $(".divider").removeClass("extra hidden");
        $(".repayment").removeClass("extra hidden");
        $(".cancelLink").addClass("hidden");
    } else if (status === 'OVERDUE') {
        $(".divider").removeClass("extra hidden");
        $(".repayment a").attr("href", "repayment/overdue");
        $(".repayment").removeClass("extra hidden");
        $(".cancelLink").addClass("hidden");
    } else if (status === 'CANCELED') {
        $(".editLink a").html('<i class="glyphicons glyphicons-edit mr5"></i>部分编辑');
        $(".cancelLink").addClass("hidden");
    } else if (status === 'CLEARED') {
        $(".cancelLink").addClass("hidden");
        $(".divider").removeClass("extra hidden");
        $(".archiveLink").removeClass("extra hidden");
    } else if (status === 'ARCHIVED') {
        $(".editLink a").html('<i class="glyphicons glyphicons-edit mr5"></i>部分编辑');
        $(".cancelLink").addClass("hidden");
    }
    if (sysEditableStatus.indexOf(status) !== -1) {
        $(".editLink").removeClass("extra hidden");
    }
    if (sysPartlyEditableStatus.indexOf(status) !== -1) {
        $(".editLink").removeClass("extra hidden");
    }
    $("li.extra").remove();
}
/**
 * 取消标的排期
 */
function cancelSchedule(a) {
    if (confirm("确定取消标的排期？取消后标的将打回【已批准】列表")) {
        var id = $(a).data("id");
        $.get("loan/cancelSchedule/" + id, function (res) {
            alert(res.message);
            if (res.success) {
                location.reload();
            }
        }).fail(function () {
            alert("服务器异常");
        });
    }
}
/**
 * 取消标的
 */
function cancel(a) {
    var confirm = "";
    var success = "";
    var fail = "";
    if($(a).html().indexOf('取消标的')==-1){
        confirm = "确定取消票据？取消后票据将放入【已取消】列表，已募集资金会退还给投资人";
        success = "票据已取消";
        fail = "票据取消失败";
    }else{
        confirm = "确定取消标的？取消后标的将放入【已取消】列表，已募集资金会退还给投资人";
        success = "标的已取消";
        fail = "标的取消失败";
    }
    sys.confirm(confirm, function (btn) {
        var id = $(a).data("id");
        var $btn = $(btn);
        sys.btnSpin($btn);
        sys.processModal();
        $.get("loan/cancel/" + id, function (res) {
            if (res.success) {
                alert("标的已取消");
                location.reload();
            } else {
                alert("标的取消失败");
                sys.closeModal();
                sys.btnStop($btn);
            }
        }).fail(function () {
            alert("网络通信错误");
            sys.closeModal();
            sys.btnStop($btn);
        });
    });
}
/**
 * 存档标的
 */
$("#loanList").on("click", ".archiveLink", function (e) {
    if (confirm("确定存档标的？")) {
        var id = $(this).data("id");
        $.get("loan/archive/" + id, function (res) {
            if (res.success) {
                alert("标的已存档");
                location.reload();
            } else {
                alert("标的存档失败");
            }
        }).fail(function () {
            alert("网络通信错误");
        });
    }
});